package com.sgb.kjwl.view.ui.activity.self;

import android.content.Context;
import android.content.Intent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.lifecycle.Observer;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityApprovalManagerBinding;
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent;
import com.sgb.kjwl.di.manage.EnterpriseManageModule;
import com.sgb.kjwl.model.entity.self.ApplyTypeData;
import com.sgb.kjwl.model.entity.transport.TabEntity;
import com.sgb.kjwl.view.ui.adapter.transport.SimpleTabAdapter;
import com.sgb.kjwl.view.ui.fragment.self.ApprovalManagerFragment;
import com.sgb.kjwl.view.widget.PickHallBidingPopWindow;
import com.sgb.kjwl.viewmodel.self.ApprovalManagerViewModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.util.PickSelectEntity;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * @author: 王彬臣
 * @date: 2021/2/20
 * @Description: 审批管理列表
 */
public class ApprovalManagerActvity extends AppActivity {
    ArrayList<Fragment> fragments = new ArrayList<>();
    private List<TabEntity> mTabs;
    private SimpleTabAdapter mAdapter;
    ActivityApprovalManagerBinding binding;
    List<ApplyTypeData> applyTypeData=new ArrayList<>();
    String[ ] titles = {"待审批","我发起","已审批","抄送我","全部"};

    private PickHallBidingPopWindow mPopup;

    private int currentPosition = 0;//当前tab指示器的位置
    @Inject
    ApprovalManagerViewModel mViewModel;

    private String mApplyType = "";//二级审批类型

    private List<PickSelectEntity> mReallyData = new ArrayList<>();

    private ApprovalPageAdapter mApprovalPageAdapter;

    public static void start(Context context,int tabpostion) {
        Intent intent=new Intent(context, ApprovalManagerActvity.class);
        intent.putExtra("tab", tabpostion);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        super.setupActivityComponent(appComponent);
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent).
                enterpriseManageModule(new EnterpriseManageModule()).build().inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_approval_manager);
        binding.setLifecycleOwner(this);
        binding.includeTitle.titleView.setText("审批列表");
        binding.includeTitle.ivBack.setOnClickListener(this);
        binding.linLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Glide.with(ApprovalManagerActvity.this).load(R.drawable.common_zhankai).into(binding.ivCommonView);
                showPopWindow();
            }
        });
        initFragment();
        mViewModel.getAgentApplyType(this);
        mViewModel.getMApplyTypes().observe(this, new Observer<List<ApplyTypeData>>() {
            @Override
            public void onChanged(List<ApplyTypeData> applyTypeData) {
                mReallyData.clear();
                PickSelectEntity reallyEntity;
                if (applyTypeData != null && !applyTypeData.isEmpty()) {
                    for (ApplyTypeData entity : applyTypeData) {
                        reallyEntity = new PickSelectEntity();
                        reallyEntity.setProjectscale(entity.getValue());
                        reallyEntity.setNo(entity.getKey());
                        mReallyData.add(reallyEntity);
                    }
                    mReallyData.add(0, new PickSelectEntity("", "全部"));
                    initSecondTab(mReallyData);
                }
                binding.linLl.setVisibility(View.VISIBLE);
            }
        });
    }

    //设置二级tab
    private void initSecondTab(List<PickSelectEntity> mReallyData) {
        if (mReallyData.isEmpty())return;
        for (int i = 0; i < mReallyData.size(); i++) {
            TabLayout.Tab tab = binding.secondTabLayout.newTab();
            tab.setText(mReallyData.get(i).getProjectscale());
            binding.secondTabLayout.addTab(tab);
//            if (i == 0) {
//                tab.view.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
//                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) tab.view.getLayoutParams();
//                layoutParams.width = SizeUtils.dp2px(52);
//                layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
//                layoutParams.gravity = Gravity.LEFT | Gravity.CENTER_VERTICAL;
//                tab.view.setLayoutParams(layoutParams);
//                tab.view.postInvalidate();
//                try {
//                    //Field mTabStripField = binding.secondTabLayout.getClass().getDeclaredField("slidingTabIndicator");
//                    //mTabStripField.setAccessible(true);
//                    //LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(binding.secondTabLayout);
//
////                    Field textView = tab.view.getClass().getDeclaredField("textView");
////                    textView.setAccessible(true);
////                    TextView tv = (TextView) textView.get(tab.view);
//                } catch (Exception e){
//
//                }
//            }
        }
        setTabLayoutPosition(currentPosition);

        binding.secondTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                setFragmentType(true, binding.vpCargoManage.getCurrentItem(), tab.getPosition());
                currentPosition = tab.getPosition();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void initFragment() {
        //viewPager适配器

//        for (int i = 0; i < titles.length; i++) {
//            ApprovalManagerFragment approvalManagerFragment = ApprovalManagerFragment.newInstance(i);
//            fragments.add(approvalManagerFragment);
//        }
        //FragPagerAdapter pagerAdapter = new FragPagerAdapter(getSupportFragmentManager(), fragments);

        mApprovalPageAdapter = new ApprovalPageAdapter(getSupportFragmentManager());
        binding.vpCargoManage.setAdapter(mApprovalPageAdapter);
        binding.vpCargoManage.setOffscreenPageLimit(titles.length);
        binding.tablayout.setupWithViewPager(binding.vpCargoManage);

        int tab = getIntent().getIntExtra("tab",0);
        binding.vpCargoManage.setCurrentItem(tab ,false);
        binding.vpCargoManage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setFragmentType(false, position, 0);
                if (binding.secondTabLayout.getTabCount() != 0) {
                    binding.secondTabLayout.getTabAt(0).select();
                }
                currentPosition = 0;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //setFragmentType(0, 0);//初始状态
    }

    //设置当前选择的二级
    private void setFragmentType(boolean isSecond, int position, int secondPosition) {
        if (secondPosition < mReallyData.size()){
            mApplyType = mReallyData.get(secondPosition).getNo();
        }
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(
                "android:switcher:" + binding.vpCargoManage.getId() + ":" + position);
        if (fragment instanceof ApprovalManagerFragment) {
            ((ApprovalManagerFragment)fragment).setSecondType(mApplyType, isSecond);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;

        }
    }


    /*
     * 多Tab展示PopWindow界面
     * */
    private void showPopWindow() {
        if (mPopup == null) {
            mPopup = new PickHallBidingPopWindow(this);
            mPopup.setBgView(binding.grayLayout);
            mPopup.setOnResultClick(new BasePopWindow.OnResultClick() {
                @Override
                public void result(Object key1, Object key2, Object key3) {
                    PickSelectEntity entity = (PickSelectEntity) key1;
                    //binding.viewpager.setCurrentItem(position);
                    mApplyType = entity.getNo();
                    currentPosition = (int) key3;
                    setTabLayoutPosition(currentPosition);
                }
            });
            mPopup.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
                @Override
                public void disMiss() {
                    Glide.with(ApprovalManagerActvity.this).load(R.drawable.common_shouqi).into(binding.ivCommonView);
                }
            });
            mPopup.setData(mReallyData);
        }
        mPopup.showPopwindow0(binding.secondTabLayout);
        mPopup.setDefItem(currentPosition);
    }

    //设置二次tab选中的位置
    private void setTabLayoutPosition(int currentPosition) {
        if (currentPosition < binding.secondTabLayout.getTabCount()) {
            binding.secondTabLayout.getTabAt(currentPosition).select();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    class ApprovalPageAdapter extends FragmentPagerAdapter {

        public ApprovalPageAdapter(@NonNull @NotNull FragmentManager fm) {
            super(fm);
        }

        @NonNull
        @NotNull
        @Override
        public Fragment getItem(int position) {
            return ApprovalManagerFragment.newInstance(position);
        }

        @Override
        public int getCount() {
            return titles.length;
        }

        @Nullable
        @org.jetbrains.annotations.Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }
}
